package cn.mini.mybatis.mybatis.session.defaults;

import cn.mini.mybatis.mybatis.executor.Executor;
import cn.mini.mybatis.mybatis.executor.resultset.DefaultResultSetHandler;
import cn.mini.mybatis.mybatis.executor.resultset.ResultSetHandler;
import cn.mini.mybatis.mybatis.mapping.MappedStatement;
import cn.mini.mybatis.mybatis.session.Configuration;
import cn.mini.mybatis.mybatis.session.SqlSession;
import lombok.extern.slf4j.Slf4j;

import java.util.List;


@Slf4j
public class DefaultSqlSession implements SqlSession {

    private final Configuration configuration;

    private Executor executor;

    public DefaultSqlSession(Configuration configuration,Executor executor) {
        this.configuration = configuration;
        this.executor = executor;
    }

    @Override
    public <E> E selectOne(String statement, Object parameter) {
        MappedStatement ms = configuration.getMappedStatement(statement);
        ResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor, ms,ms.getSqlSource().getBoundSql(parameter));
        List<E> list = executor.query(ms, parameter,resultSetHandler
                , ms.getSqlSource().getBoundSql(parameter));
        return list.get(0);
    }

    @Override
    public <E> List<E> selectList(String statement, Object parameter) {
        return null;
    }

    @Override
    public int insert(String statement, Object parameter) {
        return 0;
    }

    @Override
    public int update(String statement, Object parameter) {
        return 0;
    }

    @Override
    public int delete(String statement, Object parameter) {
        return 0;
    }

    @Override
    public <T> T getMapper(Class<T> type) {
        // 使用 Java 的动态代理生成 Mapper 接口的代理对象
        return configuration.getMapper(type,this);
    }

    @Override
    public Configuration getConfiguration() {
        return configuration;
    }
}
